package com.hospital.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hospital.system.entity.User;
import com.hospital.system.entity.UserRole;
import com.hospital.system.service.UserService;
import com.hospital.util.DataGridView;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	UserService userService;
	@RequestMapping("/login")
	public String doLogin(String loginname, String password,Model model,HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginname, password);
		try {
			subject.login(token);
			User user = userService.findUserByLoginname(loginname);
			//登陆成功，将用户存入session中
			request.getSession().setAttribute("user",user);
			//登陆成功，将用户信息存入session中
			model.addAttribute("user_id",user.getUser_id());
			model.addAttribute("realname",user.getRealname());
			//将用户真实姓名存入session
			//跳转到首页
			return "/views/index";
		} catch (UnknownAccountException e) {
			model.addAttribute("msg", "用户名不存在！");
		}catch (IncorrectCredentialsException e) {
			model.addAttribute("msg", "密码错误！");
		}
		return "/views/login";
	}
	//查找所有的用户
	@ResponseBody
	@RequestMapping("/selectAllUser")
	public Object selectAllUser(User user,Integer page,Integer limit) {
		PageHelper.startPage(page, limit);
	    List<User> allUser = userService.selectAllUser(user);
		PageInfo<User> pageInfo= new PageInfo<User>(allUser);
		Map<String, Object> tableData = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        tableData.put("code", 0);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", pageInfo.getTotal());
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", pageInfo.getList());
        return tableData;
	}
	@ResponseBody
	@RequestMapping("/addUser")
	public String addUser(User user) {
		User users = userService.findUserByLoginname(user.getLoginname());
		if (users!=null) {
			return "登录名称已存在！";
		}else {
			 //加盐
            String salt = UUID.randomUUID().toString().substring(0,4);
            //MD5加密迭代1次
            Md5Hash md5Hash = new Md5Hash("123456", salt, 1);
            String md5password = md5Hash.toString();
            //封装user对象
            user.setPassword(md5password);
            user.setSalt(salt);
            int i = userService.addUser(user);
            if (i > 0) {
                return "添加成功";
            } else {
                return "添加失败";
            }
		}
		
	}
	/**
	 * 更新用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateUser")
	public String updateUser(User user) {
		//
		User users = userService.findUserByLoginname(user.getLoginname());
		if (users!=null&&users.getUser_id()!=user.getUser_id()) {
			return "登录名称已存在！";
		}else {
            int i = userService.updateUser(user);
            if (i > 0) {
                return "修改成功";
            } else {
                return "修改失败";
            }
		}
       
	}
	@ResponseBody
	@RequestMapping("/deleteUser")
	public String deleteUser(Integer user_id) {
		userService.deleteUser(user_id);
		return "删除成功";
	}
	
	/*
	 * 初始化用户分配角色
	 */
	@RequestMapping("initUserRole")
	@ResponseBody
	public DataGridView initUserRole(Integer user_id) {
		return userService.queryUserRole(user_id);
	}
	/*
              * 保存用户和角色的关系
     * */
    @RequestMapping("saveUserRole")
    @ResponseBody
    public Object saveUserRole(UserRole userRole){
        userService.saveUserRole(userRole);
        return "分配成功";
    }

	/*
	 * 修改资料
	 */
	@RequestMapping("editLogin")
	@ResponseBody
	public Object editLogin(User user) {
		int i = userService.editLogin(user);
		if (i == 1) {
			return "修改成功";
		} else {
			return "修改失败";
		}
	}
	/*
	 * 修改资料
	 */
	@RequestMapping("editPwd")
	@ResponseBody
	public Object editLoginPwd(User user,String loginname,String pwd,String pwd1) {
		//第一步：建立subject
        Subject subject = SecurityUtils.getSubject();
        //第二步：封装token  凭证
        UsernamePasswordToken token = new UsernamePasswordToken(loginname, pwd);
      //只要能通过认证就能通过了
        try {
	        subject.login(token);
	        //加盐
            String salt = UUID.randomUUID().toString().substring(0,4);
            //MD5加密迭代1次
            Md5Hash md5Hash = new Md5Hash(pwd1, salt, 1);
            String md5password = md5Hash.toString();
            //封装user对象
            user.setPassword(md5password);
            user.setSalt(salt);
	        userService.editPwd(user);
	        return "1";//修改成功
	    } catch (IncorrectCredentialsException e) {
	        return "0";//密码错误
	    }
}
}
